﻿using System;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using Coolite.Ext.Web;
using Microsoft.Practices.ServiceLocation;
using Pap.Core.Utilities;
using Pap.Data;
using Pap.Data.Abstraction.Utils;
using Pap.Web.Utils;

namespace Quadz.LMS.MasterPage
{
    /// <summary>
    /// 
    /// </summary>
    public partial class Core : System.Web.UI.MasterPage
    {
        #region [ Session ]

        /// <summary>
        /// Gets or sets the current language.
        /// </summary>
        /// <value>
        /// The current language.
        /// </value>
        protected string CurrentLanguage
        {
            get { return Session["Language"] != null ? Session["Language"].ToString() : null; }
            set
            {
                Session["Language"] = value;
            }
        }

        #endregion

        private bool? isMainCommittee = null;

        /// <summary>
        /// Handles the Load event of the Page control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Ext.IsAjaxRequest && !this.IsPostBack)
            {
                btnWelcome.Text += (Page.User.Identity.Name);
                if (CurrentLanguage == "ar-EG")
                {
                    pnlMainMenuEnglish.Visible = false;
                    miArabic.Checked = true;
                }
                else
                {
                    pnlMainMenuArabic.Visible = false;
                    miEnglish.Checked = true;
                }

            }
            //---------------------------------------------------------
            int panelIndex = 0;
            foreach (SiteMapNode node in SiteMap.RootNode.ChildNodes)
            {
                //cannot add one panel in 2 containers
                var leftPanel = new Coolite.Ext.Web.MenuPanel() { Title = node.Title };
                var rightPanel = new Coolite.Ext.Web.MenuPanel() { Title = node.Title };

                accLeftNav.Items.Add(leftPanel);
                accRightNav.Items.Add(rightPanel);

                if (SiteMap.CurrentNode != null && node == SiteMap.CurrentNode.ParentNode)
                {
                    accLeftNav.ExpandPanel(panelIndex);
                    accRightNav.ExpandPanel(panelIndex);
                }

                CreateNavItems(node, leftPanel, rightPanel);
                panelIndex++;
            }
        }

        /// <summary>
        /// Creates the nav items.
        /// </summary>
        /// <param name="node">The node.</param>
        /// <param name="leftPanel">The left panel.</param>
        /// <param name="rightPanel">The right panel.</param>
        private void CreateNavItems(SiteMapNode node, MenuPanel leftPanel, MenuPanel rightPanel)
        {
            foreach (SiteMapNode subNode in node.ChildNodes)
            {
                var showForMainBranchOnly = Convert.ToBoolean(subNode["ShowForMainBranchOnly"]);
                bool show = true;
                if (showForMainBranchOnly)
                {
                    if (isMainCommittee == null)
                    {
                        var currentCommitte =
                            ServiceLocator.Current.GetInstance<IAdministrationRepository>().GetCommitteeByID(
                                RegistryInfo.CommitteeID);
                        isMainCommittee = currentCommitte.IsMainCommittee.GetValueOrDefault(false);
                    }
                    show = isMainCommittee.GetValueOrDefault(false);
                }
                if (show)
                {
                    HyperLinkMenuItem leftlnk = new HyperLinkMenuItem
                                                    {
                                                        NavigateUrl = subNode.Url,
                                                        Text = subNode.Title,
                                                        ToolTip = subNode.Description,
                                                        Icon = Icon.ArrowRight,
                                                        Cls = "nav-menu-item"
                                                    };
                    HyperLinkMenuItem rightlnk = new HyperLinkMenuItem
                                                     {
                                                         NavigateUrl = subNode.Url,
                                                         Text = subNode.Title,
                                                         ToolTip = subNode.Description,
                                                         Icon = Icon.ArrowRight,
                                                         Cls = "nav-menu-item"
                                                     };

                    leftPanel.Menu.Items.Add(leftlnk);
                    rightPanel.Menu.Items.Add(rightlnk);
                }
            }
        }

        /// <summary>
        /// Handles the click event of the miLogout control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void miLogout_click(object sender, EventArgs e)
        {
            FormsAuthentication.SignOut();
            FormsAuthentication.RedirectToLoginPage("Mode=Logout");
        }

        #region [ Language switching ]
        /// <summary>
        /// Arabics the checked.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The <see cref="Coolite.Ext.Web.AjaxEventArgs"/> instance containing the event data.</param>
        protected void ArabicChecked(object sender, AjaxEventArgs e)
        {
            CurrentLanguage = "ar-EG";
            this.Response.Redirect(this.Request.Url.LocalPath + "?" + this.Request.QueryString);
        }

        /// <summary>
        /// Englishes the checked.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The <see cref="Coolite.Ext.Web.AjaxEventArgs"/> instance containing the event data.</param>
        protected void EnglishChecked(object sender, AjaxEventArgs e)
        {
            CurrentLanguage = "en-US";
            this.Response.Redirect(this.Request.Url.LocalPath + "?" + this.Request.QueryString);
        }
        #endregion

        /// <summary>
        /// Handles the Clicked event of the btnHome control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="Coolite.Ext.Web.AjaxEventArgs"/> instance containing the event data.</param>
        protected void btnHome_Clicked(object sender, AjaxEventArgs e)
        {
            this.Response.Redirect("~/");
        }

        /// <summary>
        /// Handles the Clicked event of the BtnChangePassword control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="Coolite.Ext.Web.AjaxEventArgs"/> instance containing the event data.</param>
        protected void BtnChangePassword_Clicked(object sender, AjaxEventArgs e)
        {
            using (IUnitOfWork trans = ServiceLocator.Current.GetInstance<IUnitOfWork>())
            {
                IMembershipRepository membershipRepositoryInst = ServiceLocator.Current.GetInstance<IMembershipRepository>();
                var currentUser = membershipRepositoryInst.GetUserByID(RegistryInfo.UserID);
                if (currentUser.Password.Equals(txtOldPassword.Text))
                {
                    if (txtNewPassword.Text.Equals(txtNewPasswordConfirm.Text))
                    {
                        currentUser.Password = txtNewPassword.Text;
                        trans.Commit();
                        wndChangePassword.Hide();
                    }
                    else
                    {
                        Ext.Msg.Show(new MessageBox.Config
                        {
                            Title = GetLocalResourceObject("wndWrongPassTitle").ToString(),
                            Message = GetLocalResourceObject("wndWrongPassMSG").ToString()
                        });
                    }
                }
                else
                {
                    Ext.Msg.Show(new MessageBox.Config
                    {
                        Title = GetLocalResourceObject("wndWrongOldPassTitle").ToString(),
                        Message = GetLocalResourceObject("wndWrongOldPassMSG").ToString()
                    });
                }
            }
        }

        /// <summary>
        /// Handles the Clicked event of the MiPassword control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="Coolite.Ext.Web.AjaxEventArgs"/> instance containing the event data.</param>
        protected void MiPassword_Clicked(object sender, AjaxEventArgs e)
        {
            txtOldPassword.Reset();
            txtNewPassword.Reset();
            txtNewPasswordConfirm.Reset();
            wndChangePassword.Show();
        }
    }
}
